package com.hzy.yiyaoba.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;

import com.hzy.yiyaoba.R;
import com.hzy.yiyaoba.R.id;

public class MainActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = getSimpleName(MainActivity.class);
	private static final int TAB_COUNT = 4;

	private Fragment[] mFragments = new Fragment[TAB_COUNT];
	private List<TextView> mTabButtons = new ArrayList<TextView>();
	private FragmentManager mFragmentManager;

	@Override
	protected void onCreate(Bundle arg0) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(arg0);
	}

	@Override
	protected void initEnvironment() {
		mFragmentManager = getSupportFragmentManager();
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.activity_main;
	}

	@Override
	protected void initView() {
		mTabButtons.add((TextView) findViewById(id.main_activity_lore_btn));
		mTabButtons.add((TextView) findViewById(id.main_activity_ask_btn));
		mTabButtons.add((TextView) findViewById(id.main_activity_book_btn));

		for (TextView t : mTabButtons) {
			t.setOnClickListener(this);
		}

		setSection(0);
	}

	private void setSection(int index) {
		FragmentTransaction trans = mFragmentManager.beginTransaction();
		for (int i = 0; i < mFragments.length; i++) {
			Fragment frag = mFragments[i];
			if (index == i) {
				if (frag != null) {
					trans.show(frag);
				} else {
					frag = newFragmentByIndex(frag, i);
					mFragments[i] = frag;
					trans.add(id.main_activity_main_area, frag);
				}
			} else {
				if (frag != null) {
					trans.hide(frag);
				}
			}
		}
		trans.commit();
		mTabButtons.get(index).setSelected(true);
	}

	private Fragment newFragmentByIndex(Fragment frag, int index) {
		switch (index) {
		case 0:
			frag = new LoreFragment();
			break;
		case 1:
			frag = new AskFragment();
			break;
		case 2:
			frag = new BookFragment();
			break;
		case 3:
			frag = new LoreFragment();
			break;
		default:
			break;
		}
		return frag;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case id.main_activity_lore_btn:
			setSection(0);
			break;
		case id.main_activity_ask_btn:
			setSection(1);
			break;
		case id.main_activity_book_btn:
			setSection(2);
			break;
		default:
			break;
		}
	}

}
